package fr.vincent7894.feedroid.utils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import android.net.http.AndroidHttpClient;
import fr.vincent7894.feedroid.var.Const;

public class NetworkUtils {

	private static final HttpClient HTTP_CLIENT = AndroidHttpClient
			.newInstance(Const.APP_NAME);

	public static InputStream httpGet(String uri) throws Exception {
		InputStream inputStream = null;

		HttpResponse response = null;
		synchronized (HTTP_CLIENT) {
			response = HTTP_CLIENT.execute(new HttpGet(uri));
		}
		
		HttpEntity entity = response.getEntity();
		inputStream = entity.getContent();

		return inputStream;
	}

	
	public static InputStream httpPost(String uri, Map<String, Object> datas) throws Exception {
		InputStream inputStream = null;
		HttpResponse response = null;
		HttpPost post = new HttpPost(uri);
		
		Set<Entry<String, Object>> entries = datas.entrySet();
		List<NameValuePair> params = new ArrayList<NameValuePair>(entries.size());
		
		// Fill datas
		for(Entry<String, Object> entry : entries) {
			params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
		}
		
		post.setEntity(new UrlEncodedFormEntity(params));
		
		synchronized (HTTP_CLIENT) {
			response = HTTP_CLIENT.execute(post);
		}
		
		HttpEntity entity = response.getEntity();
		inputStream = entity.getContent();

		return inputStream;
	}
	
	public static void clean() {
		HTTP_CLIENT.getConnectionManager().shutdown();
	}
}
